package com.golang.api.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
//import org.zhaolei.model.LoginUser;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

@Slf4j
public class JWTUtil {

    /**
     * 过期时间，设置为3天
     */
    private static final long EXPIRE = 1000L * 60 * 60 * 24 * 10 * 3;

    /**
     * 加密的秘钥，自定义的
     */
    private static final String SECRET = "QULANG6v9yBEHMcQfTjWnZr4u7xADG123456ABCDEFGHIJKKQWERTYUIOP";

    /**
     * 令牌前缀，自定义的
     */
    private static final String TOKEN_PREFIX = "qulang1024club";

    /**
     * subject，自定义的
     */
    private static final String SUBJECT = "QULANGCOMPANY";

    /**
     * 根据手机号生成token
     * @param phoneNum
     * @return
     */
    public static String geneJsonWebToken(String openId) {
        if (openId == null || openId.isEmpty()) {
            throw new NullPointerException("openId为空");
        }

        String token = Jwts.builder().setSubject(SUBJECT)
                //payload
                .claim("openId", openId)
//                .claim("name", loginUser.getName())
//                .claim("head_img", loginUser.getHeadImg())  ///为什么加上headimg的地址解析时会出问题？？？？？
//                .claim("mail", loginUser.getMail())
                //signature
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, SECRET).compact();

        token = TOKEN_PREFIX + token;
        return to32BitHash(token);
    }

    private static String to32BitHash(String input) {
        try {
            // 1. 使用MD5算法（输出128位/16字节）
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 2. 计算哈希值
            byte[] digest = md.digest(input.getBytes());

            // 3. 转换为32字符十六进制表示
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString(); // 16字节 → 32字符十六进制
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 校验token是否正确
     * @param token
     * @return
     */
    public static Claims checkJWT(String token) {
        try {
            final Claims claims = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody();

            return claims;
        } catch (Exception e) {
            log.error("token解析失败:{}", token, e);
            return null;
        }
    }
}
